<?php

namespace app\index\traits;

use app\common\model\Area;
use app\common\model\RankBroadcast;
use app\common\model\Trade;
use app\index\service\BroadcastService;
use ShidianUtil\Utils\TimeUtil;

/**
 * 订单实时播报
 * Trait TradeBroadcastTrait
 * @package app\index\traits
 */
trait TradeBroadcastTrait
{

    /**
     * 添加实时播报
     * @param $provinceId
     * @return void
     */
    private function addBroadcast($provinceId): void
    {
        if (!is_id($provinceId)) {
            return;
        }

        $provinceName = Area::where('id', $provinceId)->value('name');

        if (is_blank($provinceName)) {
            return;
        }

        // 订单类型
        $tradeTypes = [
            TRADE_CONSULTING_SERVER,
            TRADE_LAWSUIT,
            TRADE_LANDING,
        ];

        $tableName = Trade::getTable();
        $total = Trade::leftJoin('consulting c', "$tableName.consultingId = c.id")
                      ->where('c.provinceId', $provinceId)
                      ->where("$tableName.payStatus", Trade::PAID)
                      ->where("$tableName.payTime", '>=', TimeUtil::stamp(TimeUtil::DAY))
                      ->whereIn('tradeType', $tradeTypes)
                      ->count();

        $message = [
            ['type' => 'text', 'red' => 102, 'text' => '新增1笔订单，今日累计'],
            ['type' => 'text', 'red' => 101, 'text' => $total],
            ['type' => 'text', 'red' => 102, 'text' => ' 笔'],
        ];

        $this->getBroadcastService()->addBroadcast(RankBroadcast::DINGDAN, 0, $provinceName, $message);
    }

    private function getBroadcastService(): BroadcastService
    {
        return app(BroadcastService::class);
    }
}